﻿using System;
using System.Collections.Generic;
using System.IO;
using Compiler.Primitives;

namespace Compiler.Modules
{
    class Compiler
    {
        private readonly List<string> _output;

        public Compiler()
        {
            _output = new List<string>();

            Convert();

            //Output to the same directory as the source file - we may want to change this at some point in the future
            var outputFile = Hub.GetSource().Substring(0, Hub.GetSource().LastIndexOf(".", StringComparison.Ordinal)) + ".bvm";

            if (File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }

            var sr = new StreamWriter(outputFile);
            
            foreach (var line in _output)
            {
                sr.WriteLine(line);
            }

            sr.Close();

            Environment.Exit(0);
        }

        public void Convert()
        {
            foreach (var clss in Hub.GetClasses())
            {
                _output.Add("class " + clss.GetName() + "\n");

                ConvertClass(clss);

                _output.Add("end class");
            }
        }

        public void ConvertClass(Class clss)
        {
            foreach (var func in clss.GetFunctions())
            {
                _output.Add("func " + func.GetName());

                ConvertFunction(func);

                _output.Add("end func\n");
            }
        }

        public void ConvertFunction(Function func)
        {
            foreach (var line in func.GetCode())
            {
                switch (StringParser.GetKeyword(line).Trim().ToUpper())
                {
                    case "CONSOLE.WRITELINE":
                        /*
                         * Use the _output list to add the converted code to
                         * for example _output.Add("prnt string")
                         */
                        break;
                }
            }
        }
    }
}
